# -*- coding:utf-8 -*-
"""
@Author : 审心
@Time : 2023/5/6 17:26
"""
import sys
import time
import traceback
from dataclasses import dataclass
import random
from typing import Tuple

from DrissionPage import WebPage

from autoTask.taobao.sycm.gjc.competitorGoodKey.getCompetingKeyAction import CacheAction
from common.logger.log import log_
from autoTask.taobao.sycm.gjc.competitorGoodKey import GoodsFeature
from autoTask.taobao.sycm.gjc.competitorGoodKey.publicResource import get_xws_copy_action_content, wait_tb_complete
from common.utils import urlUtil, StrUtil, ObjUtil
from common.utils.web_page_util import MockTap, Input, ActionChain, Tap, wait_ele_text_range


@dataclass
class GetContrastData:
    """
    获取竞争商品对比数据
    Attributes:
        p: 网页对象
        goods_info: 商品相关信息
    """
    p: WebPage
    goods_info: GoodsFeature

    def __call__(self) -> Tuple[str, str, str]:
        result = ()
        try:
            # 先从缓存获取
            result = CacheAction.CompetingContrast.get(gf=self.goods_info)
            if ObjUtil.has_none(result):
                self.to_init_page()
                self.set_data_condition()
                result = (self.get_content1(), self.get_content2(), self.get_content3())
        except:
            log_.warning(f"获取竞品数据失败 商品信息 : {self.goods_info}")
            log_.error(f"{sys.exc_info()[0]} {sys.exc_info()[1]}")
            log_.error(traceback.format_exc())
        else:
            if ObjUtil.has_none(result[0], result[2]):
                log_.warning(f"获取竞品数据失败 商品信息 : {self.goods_info}")
            else:
                # 存入缓存
                CacheAction.CompetingContrast.put(gf=self.goods_info, content_tuple=result)
        return result

    def to_init_page(self):
        """
        跳转到当前任务首页(商品竞品分析页面)
        :return:
        """
        if not self.p.url.startswith("https://sycm.taobao.com/mc/ci/item/analysis"):
            MockTap(self.p("x://span[.='竞争']"), "跳转到 [竞争] 标签页失败", before_delay=(1, 3))()
            self.p.wait.load_complete(30)
        params = urlUtil.parse_url(self.p.url).get("params")
        goods_list = [params.get("rivalItem1Id"), params.get("rivalItem2Id"), params.get("selfItemId")]
        is_already_set_goods = StrUtil.non_any_blank(goods_list)
        is_target_view = not ObjUtil.has_none(goods_list)
        if is_target_view or is_already_set_goods:
            MockTap(self.p("x://span[.='竞品分析']"), "跳转到 [竞品分析] 标签页失败", before_delay=(1, 3))()
            self.p.wait.load_complete(30)

    def set_data_condition(self):
        """
        设置页面的数据条件
        :return:
        """
        date_ele = self.p(f"tag:span@@text()={self.goods_info.date_cycle}")
        if self.goods_info.date_cycle == "30天" and not date_ele:
            date_ele = self.p("tag:span@@text()=7天")
        MockTap(date_ele, "设置数据周期时失败")()

        # 以下所需要的 获取元素的映射 add : 添加框 search :  搜索框 firstSelect : 搜索出的第一个元素 goods_id : 搜索框需要填入的商品id
        xpath_map = [
            {"add": 'x://*[@id="sycm-mc-ci-item-analysis-select"]/div[2]/span/div[1]/span',
             "goods_id": self.goods_info.goods_id},
            {"add": 'x://*[@id="sycm-mc-ci-item-analysis-select"]/div[2]/span/div[2]/span',
             "goods_id": self.goods_info.competing1},
            {"add": 'x://*[@id="sycm-mc-ci-item-analysis-select"]/div[2]/span/div[3]/span',
             "goods_id": self.goods_info.competing2},
        ]
        # 随机排列一下
        random.shuffle(xpath_map)
        self.p.scroll.to_top()
        for item in xpath_map:
            MockTap(self.p(item['add']), f"点击添加商品框时失败 参数 : {item}",
                    before_delay=(1, 3), after_delay=(1, 3), reduce_scope=(20, 3))()
            # 获取打开的下拉窗
            dropdown = self.p("x://div[@class='ant-dropdown ant-dropdown-placement-bottomLeft']")
            # 获取搜索输入框
            Input(dropdown("t:input"), "输入商品编号失败", vals=item['goods_id'], after_delay=(4, 6))()
            # 获取第一个选项元素
            MockTap(dropdown(".oui-typeahead-dropdown-item"), f"点击搜索结果首选项时失败 参数 : {item}",
                    after_delay=(1, 3))()

    def get_content1(self):
        # 复制关键指标对比
        ActionChain(self.p)([
            Tap("text:小旺神一键转化", "点击小旺神一键转化失败", after_delay=(2, 3)),
            Tap('x://*[@id="pane-0"]//div[1]//span/button', "初始化表格列时 - 打开列设置失败", after_delay=2),
            Tap("c:[x-placement='top'] .el-button--small > span", "初始化表格列时 - 恢复默认失败", after_delay=2),
            Tap("c:[x-placement='top'] .el-button--primary > span", "初始化表格列时 - 确定列设置失败",
                after_delay=2),
        ])
        th_col = self.p("c:.el-table--scrollable-y .el-table__fixed-header-wrapper tr").eles("t:th")
        return get_xws_copy_action_content(self.p, th_col, 15,
                                           "x://div[@class='el-tab-pane']//span[contains(.,'一键复制')]")

    def get_content2(self):
        # 滚动到底部 复制流量来源流量结构
        self.p.scroll.to_bottom()
        time.sleep(5)
        if not self.p('x://*[@id="sycm-mc-ci-item-analysis-flow-source-new"]/div[2]/div[2]/div[1]//div[2]'):
            ActionChain(self.p)([
                Tap('x://*[@id="xws-item-flow-analysis-new"]/button', "点击小旺神一键转化失败", after_delay=(2, 3)),
                Tap("c:.is-plain > span", "初始化表格列时 - 打开列设置失败", after_delay=2),
                Tap("x://span[.='恢复默认']", "初始化表格列时 - 恢复默认失败", after_delay=2),
                Tap("x://div[@class='el-scrollbar__view']//div[8]//span[@class='el-switch__core']",
                    "初始化表格列时 - 关闭交易金额占比列时失败", after_delay=2, is_random=False),
                Tap(
                    "x://div[@class='el-scrollbar__view']//div[14]//span[@class='el-switch__core']",
                    "初始化表格列时 - 关闭下单买家数列时失败", after_delay=2, is_random=False),
                Tap(
                    "x://div[@class='el-scrollbar__view']//div[15]//span[@class='el-switch__core']",
                    "初始化表格列时 - 关闭下单转化率列时失败", after_delay=2, is_random=False),
                Tap("x://span[.='确认']", "初始化表格列时 - 确定列设置失败", after_delay=2),
            ])
            th_col = self.p("c:.has-gutter > tr").eles("t:th@@class:is-center   is-leaf is-sortable")
            return get_xws_copy_action_content(self.p, th_col, 10, "x://span[contains(.,'一键复制')]")
        else:
            return None

    def get_content3(self):
        # 获取入店来源数据
        self.p.scroll.to_top()
        MockTap(self.p('text=日'), "设置数据周期为 日 时失败")()
        back_date_el = self.p('.oui-date-picker-particle-button')(
            ".anticon anticon-angle-left oui-canary-icon oui-canary-icon-angle-left")
        if not back_date_el:
            raise RuntimeError("获取日期后退按钮失败")
        # 积攒30天或7天内的数据到缓存
        days = 30 if self.goods_info.date_cycle == "30天" else 7
        for i in range(days):
            if self.p("@@class=oui-tab-switch-item oui-tab-switch-item-active default@@text():引流关键词",
                      timeout=0):
                MockTap(self.p("@@class=oui-tab-switch-item@@text():成交关键词", timeout=0),
                        f"跳转到成交关键词标签页时失败 下标 : {i}", after_delay=(2, 3))()
                wait_tb_complete(self.p, delay=0, loading_time=60)
            elif self.p("@@class=oui-tab-switch-item oui-tab-switch-item-active default@@text():成交关键词",
                        timeout=0):
                MockTap(self.p("@@class=oui-tab-switch-item@@text():引流关键词", timeout=0),
                        f"跳转到引流关键词标签页时失败 下标 : {i}", after_delay=(2, 3))()
                wait_tb_complete(self.p, delay=0, loading_time=60)
            else:
                raise RuntimeError("没有获取到任何一个已经激活的标签页")
            MockTap(back_date_el, "点击日期后退按钮失败", after_delay=(2, 3))()
            wait_tb_complete(self.p, delay=0, loading_time=60)
        Tap(self.p('c:#xws-kw-mday-shop span > span'), "小王神一键转化打开失败", after_delay=(2, 3))()
        # 获取页脚 数据总条数
        Tap(self.p("x://div/table/div"), "取消全部选中", after_delay=5)()
        e_total = self.p('.el-pagination__total')
        low_text = e_total.text
        es = self.p(".tbody-style")("tag:tr").eles(".xws-selector-td")
        Tap(es[0], "选择数据前区间失败", after_delay=(2, 3))()
        _, low_text = wait_ele_text_range(e_total, low_text, throw_error=True)
        Tap(es[len(es) - 1], "选择数据后区间失败", after_delay=(2, 3))()
        wait_ele_text_range(e_total, low_text, throw_error=True)
        ActionChain(self.p)([
            Tap('x://*[@id="pane-0"]//div[1]//span/button', "初始化表格列时 - 打开列设置失败", after_delay=2),
            Tap("c:[x-placement='top'] .el-button--small > span", "初始化表格列时 - 恢复默认失败", after_delay=2),
            Tap("c:[x-placement='top'] .el-button--primary > span", "初始化表格列时 - 确定列设置失败",
                after_delay=2),
        ])
        th_col = self.p("c:.has-gutter > tr").eles("t:th@@class:is-center   is-leaf is-sortable")
        return get_xws_copy_action_content(self.p, th_col, 10, "x://span[contains(.,'一键复制')]")
